package com.witframework.web.tag;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

/**
 * FormatTag - 用于格式数字或日期.
 * currency，number，date
 *
 */
public class FormatTag extends BodyTagSupport {
    private String type = "N";   
    private String pattern;
    @Override
	public int doAfterBody() throws JspException {
        NumberFormat nf = null;
        DateFormat df = null;
        BodyContent body = getBodyContent();
        String value = body.getString();
        body.clearBody();
        if (value == null || value.length() == 0)
            return SKIP_BODY;
        if (type.charAt(0) == 'C' || type.charAt(0) == 'c'){
            nf = NumberFormat.getCurrencyInstance();
            
        }
        if (type.charAt(0) == 'N' || type.charAt(0) == 'n'){
        	if(pattern==null)
        		pattern="####0.00";
            nf =new  DecimalFormat(pattern);
        }
        if (type.charAt(0) == 'D' || type.charAt(0) == 'd'){
        	if(pattern==null)
        		pattern="yyyy-MM-dd";
            df = new SimpleDateFormat(pattern);
        }
        try {
            if (nf != null) {
                // do the number formatting
            	NumberFormat strFormat =  NumberFormat.getInstance();        

                getPreviousOut().print(nf.format(strFormat.parse(value.trim())));
            } else if (df != null) {
                // do the date formatting
                getPreviousOut().print(df.format(df.parse(value.trim())));
            } else {
                // just return the value
                getPreviousOut().print(value);
            }
        } catch (Exception e) {
        	throw new JspException("Print/Flush in LoadingTag tag error:" + e);
        }
        return SKIP_BODY;
    }
    
    public void setType(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }

	public void setPattern(String pattern) {
		this.pattern = pattern;
	}


}
